import { Plugin } from "siyuan"
import { createApp } from 'vue'
import App from './App.vue'

let plugin: Plugin | null = null
let app: any = null

export function usePlugin(pluginProps?: Plugin): Plugin {
  if (pluginProps) plugin = pluginProps
  if (!plugin) {
    console.error('需要绑定插件实例，请在插件的main.ts中调用usePlugin(plugin) 绑定插件实例')
  }
  return plugin!
}

export function init(plugin: Plugin) {
  usePlugin(plugin)

  const div = document.createElement('div')
  div.classList.toggle('my-plugin-app')
  div.id = this.name
  
  app = createApp(App)
  app.mount(div)
  document.body.appendChild(div)
}

export function destroy() {
  if (app) {
    app.unmount()
    const div = document.getElementById(this.name)
    if (div) document.body.removeChild(div)
  }
}
